package com.runen.infinitemovement.activity;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.king.zxing.util.CodeUtils;
import com.runen.infinitemovement.Constant;
import com.runen.infinitemovement.R;
import com.runen.infinitemovement.adapter.InviteFriendsAdapter;
import com.runen.infinitemovement.base.BaseActivity;
import com.runen.infinitemovement.model.api.CompanyAPI;
import com.runen.infinitemovement.model.api.UserAPI;
import com.runen.infinitemovement.model.entity.InviteFriendsEntity;
import com.runen.infinitemovement.model.entity.TenantCodeEntity;
import com.runen.infinitemovement.tool.GlideUtils;
import com.runen.infinitemovement.tool.ShareBitmapUtils;
import com.runen.infinitemovement.widget.popupwind.SharePoppupWindow;
import com.runen.rxnetlibrary.net.callback.BaseResultCallback;
import com.runen.rxnetlibrary.utils.ToastUtils;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class InviteFriendsActivity extends BaseActivity {

    @BindView(R.id.top_btn_left)
    Button topBtnLeft;
    @BindView(R.id.top_title)
    TextView topTitle;
    @BindView(R.id.tv_get_hozom)
    TextView tvGetHozom;
    @BindView(R.id.tv_invite_num)
    TextView tvInviteNum;
    @BindView(R.id.iv_shut_down)
    ImageView ivShutDown;
    @BindView(R.id.rv_invite_list)
    RecyclerView rvInviteList;
    @BindView(R.id.ll_dialog)
    LinearLayout llDialog;
    @BindView(R.id.tv_invite)
    TextView tvInvite;
    @BindView(R.id.tv_my_tenant_code)
    TextView tv_my_tenant_code;
    @BindView(R.id.rl_invit_content)
    RelativeLayout rl_invit_content;
    @BindView(R.id.ll_invit_content)
    LinearLayout ll_invit_content;
    @BindView(R.id.iv_down_app)
    ImageView iv_down_app;
    @BindView(R.id.tv_my_tenant_code_1)
    TextView tv_my_tenant_code_1;
    private InviteFriendsAdapter friendsAdapter;
    String inviteInfo = "已邀请%s位 | <font color='#FFE89A'>查看邀请记录</font>";

    private String codeUrl = "";//二维码地址

    @Override
    protected int getLayoutId() {
        return R.layout.activity_invite_friends;
    }

    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        ButterKnife.bind(this);
        topTitle.setText("邀请好友");
        String hozmInfo = "每邀请一位好友<br/>可获得<font color='#FFD910'>+10</font>颗火种";
        tvGetHozom.setText(Html.fromHtml(hozmInfo));

        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        rvInviteList.setLayoutManager(layoutManager);
        friendsAdapter = new InviteFriendsAdapter(this);
        rvInviteList.setAdapter(friendsAdapter);
        String url = String.format(Constant.INVIT_FRIEND, UserAPI.getUserId());
//        GlideUtils.loadImage(InviteFriendsActivity.this, url, iv_down_app);
        iv_down_app.setImageBitmap(CodeUtils.createQRCode(url, 600));
        initData();
        getMyTenantCode();
    }

    private void initData() {
        showDialog();
        new UserAPI().getInviteFriends(new BaseResultCallback<InviteFriendsEntity>() {
            @Override
            public void onResponse(InviteFriendsEntity response) {
                dismissDialog();
                if (response.code == 0) {
                    tvInviteNum.setText(Html.fromHtml(String.format(inviteInfo, response.count)));
                    if (response.data != null && response.data.size() > 0) {
                        friendsAdapter.setNewData(response.data);
                    }
                }
            }
        });
    }

    /**
     * 获取我的军团二维码以及code
     */
    private void getMyTenantCode() {
        new CompanyAPI().getMyTenantCode(new BaseResultCallback<TenantCodeEntity>() {
            @Override
            public void onResponse(TenantCodeEntity response) {
                if (response != null && response.code == 0) {
                    if (response.data != null) {
                        String str = "我的军团码：%s";
                        String str1 = "我的军团码：<font color='#EA3A33'>%s<font/>";
                        tv_my_tenant_code.setText(String.format(str, response.data.tenantCode));
                        tv_my_tenant_code_1.setText(Html.fromHtml(String.format(str1, response.data.tenantCode)));
                        codeUrl = response.data.tenantCodeUrl;
//                        String url = "https://futmarch-attach.oss-cn-hangzhou.aliyuncs.com/template/activity20210518113212.png";
//                        GlideUtils.loadImage(InviteFriendsActivity.this, url, iv_down_app);
                    }
                }
            }
        });
    }

    @OnClick({R.id.top_btn_left, R.id.tv_invite_num, R.id.iv_shut_down, R.id.tv_invite})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.top_btn_left:
                finish();
                break;
            case R.id.tv_invite_num:
                llDialog.setVisibility(View.VISIBLE);
                break;
            case R.id.iv_shut_down:
                llDialog.setVisibility(View.GONE);
                break;
            case R.id.tv_invite:
                rl_invit_content.setVisibility(View.VISIBLE);
                showPopup();
                break;
        }
    }

    private void showPopup() {
//        SharePoppupWindow sharePoppupWindow = SharePoppupWindow.getInstance(this,
//                "我正在挑战「重走长征路」邀您一起同行。",
//                "体验不一样的长征路，与我一起挑战吧！",
//                String.format(Constant.SHARE_INVITE_FRIENDS, UserAPI.getUserId()), 1);
//        sharePoppupWindow.show();

        SharePoppupWindow sharePoppupWindow = SharePoppupWindow.getInstance(InviteFriendsActivity.this);
        sharePoppupWindow.setBitmap(ShareBitmapUtils.savePoster(InviteFriendsActivity.this, ll_invit_content));
        sharePoppupWindow.setOnClick(new SharePoppupWindow.OnClick() {
            @Override
            public void savePic(Bitmap bitmap) {
                saveLocalPic(bitmap);
                rl_invit_content.setVisibility(View.GONE);
            }

            @Override
            public void hitCard() {
                rl_invit_content.setVisibility(View.GONE);
            }

            @Override
            public void dismiss() {
                rl_invit_content.setVisibility(View.GONE);
            }

            @Override
            public String imagePath(Bitmap bitmap) {
                return saveLocalPic(bitmap);
            }
        });
        sharePoppupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                rl_invit_content.setVisibility(View.GONE);
            }
        });
        sharePoppupWindow.show(1.0f);
    }

    /**
     * 生成海报图片
     */
    public Bitmap savePoster() {
        //获取当前屏幕的大小
        int width = getWindow().getDecorView().getRootView().getWidth();
        int height = getWindow().getDecorView().getRootView().getHeight();
        //生成相同大小的图片（用来存储截屏后生成的bitmap对象）
        Bitmap temBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
        //找到当前页面的根布局（需要截屏的View）
        View view = ll_invit_content;
        //view.getDrawingCache()==null时，需要重新测量view的宽高
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        //设置缓存
        view.setDrawingCacheEnabled(true);
        view.buildDrawingCache();
        //从缓存中获取当前屏幕的图片
        temBitmap = view.getDrawingCache().copy(Bitmap.Config.ARGB_8888, false);
        //将截屏图片保存至本地
//        saveToLocal(temBitmap);
        //销毁当前屏幕图片的缓存
        view.destroyDrawingCache();
        view.setDrawingCacheEnabled(false);
        return temBitmap;
    }

    private String imagePath;
    private static final int REQUEST_STATE_CODE = 1010;
    private Bitmap mBitmap;

    private String saveLocalPic(Bitmap bitmap) {
        // 3.保存到SD卡
        if (bitmap != null) {
            this.mBitmap = bitmap;
            //判断是否为Android 6.0 以上的系统版本，如果是，需要动态添加权限
            if (Build.VERSION.SDK_INT >= 23) {
                requestPermissions(bitmap);
            } else {
                imagePath = ShareBitmapUtils.saveToLocal(this, bitmap);
            }
        }
        return imagePath;
    }

    private void requestPermissions(Bitmap bitmap) {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            // 申请一个（或多个）权限，并提供用于回调返回的获取码（用户定义）
            ActivityCompat.requestPermissions(this, new String[]{
                    Manifest.permission.WRITE_EXTERNAL_STORAGE
            }, REQUEST_STATE_CODE);
        } else {
            imagePath = ShareBitmapUtils.saveToLocal(this, bitmap);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        switch (requestCode) {
            case REQUEST_STATE_CODE:
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    imagePath = ShareBitmapUtils.saveToLocal(this, mBitmap);
                } else {
                    ToastUtils.showLong("权限授予失败，请重新授予");
                    return;
                }
                break;
            default:
                break;
        }
    }
}
